package mvc.gui.impl;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;

import javax.swing.ImageIcon;
import mvc.core.IMachuPicchu;
import mvc.core.impl.MachuImage;

public class MainFramePresenter implements PropertyChangeListener,
		ComponentListener {

	private MainFrame panel;
	private IMachuPicchu machu;
	private BufferedImage mainStageImage;

	public MainFramePresenter(IMachuPicchu machuPicchu, MainFrame frame) {
		this.machu = machuPicchu;
		this.panel = frame;
		machu.addPropertyChangeListener(this);
		panel.addComponentListener(this);
	}
	// TODO This method should not take care of IOException, method should be removed
	private void updateImage(MachuImage mi){
		try {
			mainStageImage = machu.getImageProcessor().processImage(mi, -1, -1);
			repaintMainStage();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
/*
 * Updates the mainStage with new or processed image.
 */
	private void repaintMainStage() {
		if (machu.getSelectedImages().size() > 0) {
			MachuImage im = machu.getSelectedImages().get(0); //This will be ok when above is fixed.
			panel.imageLabel.setIcon(null);
			panel.imageLabel.setSize(panel.mainStage.getSize());
			try {
				if(mainStageImage.getWidth()> mainStageImage.getHeight()){
					panel.imageLabel.setIcon(new ImageIcon(machu.getScaledImage(mainStageImage, panel.mainStage.getWidth(), -1)));
				} else {
				panel.imageLabel.setIcon(new ImageIcon(machu.getScaledImage(mainStageImage, -1, panel.mainStage.getHeight())));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			panel.imageLabel.revalidate();
			panel.repaint();
		} else {
			panel.imageLabel.setIcon(null);
			panel.imageLabel.revalidate();
			panel.repaint();
		}
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals("selectedImagesChanged")
				|| evt.getPropertyName().equals("imageListChanged")) {
			updateImage(machu.getSelectedImages().get(0));
			repaintMainStage();
		}

	}

	@Override
	public void componentHidden(ComponentEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void componentMoved(ComponentEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void componentResized(ComponentEvent e) {
		repaintMainStage();
	}

	@Override
	public void componentShown(ComponentEvent e) {
		// TODO Auto-generated method stub

	}

}
